import axios from 'axios'
import store from '@/store'
import router from '@/router'
import storage from 'store'
import {VueAxios} from './axios'
import {ACCESS_INFO, ACCESS_TOKEN} from '@/store/mutation-types'
import {message} from 'ant-design-vue'
import Crypto from "@/utils/crypto";

const urlList = ['DataBaseEnterprise', 'AdoptEnterprise', 'CreditLineSum', 'LoanUser', 'CreditBalanceSum']
// 创建 axios 实例
const request = axios.create({
    // API 请求的默认前缀
    baseURL: process.env.NODE_ENV == 'development' ? '/api' : process.env.VUE_APP_SERVER_URL
    // timeout: 6000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
    if (error.response) {
        if (error.response.data.code === 400) {
            store.dispatch('Logout')
            router.replace('/auth/login')
        }
    }
    return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
    const token = storage.get(ACCESS_TOKEN)
    const info = storage.get(ACCESS_INFO)
    console.log('info', info)
    // 如果 token 存在
    // 让每个请求携带自定义 token 请根据实际情况自行修改
    config.headers['clientId'] = Crypto.encrypt('NB6N66Eq3cshSi8DKxmc5W5Qkc4r7p3I')
    config.headers['clientSecret'] = Crypto.encrypt('AVe5dIGES3nhrXDl3ez65XoaQaw4KMCS')
    config.headers['sign'] = Crypto.encrypt('NB6N66Eq3cshSi8DKxmc5W5Qkc4r7p3IAVe5dIGES3nhrXDl3ez65XoaQaw4KMCS')
    if (token) {
        config.headers['X-Access-Token'] = Crypto.encrypt(token)
    }
    if (info) {
        config.headers['X-Access-UserId'] = Crypto.encrypt(info.uid)
    }
    return config
}, errorHandler)

// response interceptor
request.interceptors.response.use(async (response) => {
    console.log(response)
    // 0成功，400是token失效，999999是失敗
    if (response.data.code === 400) {
        await store.dispatch('Logout')
        await router.replace('/auth/login')
        return
    }
    // response.data.msg = '密码超过一个季度未修改，请修改密码'
    if (response.data.code === 999999|| response.data.code  === 666666 || response.data.msg == '您的密码超过90天未做修改，现要求您强制更换新密码') {
        message.error(response.data.mes || response.data.msg)
        return Promise.reject(response.data)
    }
    if (Object.prototype.toString.call(response.data) === '[object Blob]') {
        return response.data
    }
    if (!response.data.data) return response.data
    for (let i = 0; i < urlList.length; i++) {
        console.log('response.config.url', response.config.url)
        if (response.config.url.includes(urlList[i])) {
            return response.data
            break
        }
    }
    return response.data && response.data.data
}, errorHandler)

const installer = {
    vm: {},
    install(Vue) {
        Vue.use(VueAxios, request)
    }
}

export default request

export {
    installer as VueAxios,
    request as axios
}
